<?php

declare(strict_types=1);

namespace App\Chat\Service;

use App\Common\Robot\Contracts\GatewayInterface;
use App\Common\Robot\Robot;
use App\CustHub\Mapper\ChEmployeeMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChContact;
use App\CustHub\Model\ChEmployee;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use function Hyperf\Collection\collect;

class EmployeeService extends AbstractService
{
    public $mapper;

    #[Inject]
    protected ChRobotMapper $robotMapper;

    public function __construct(ChEmployeeMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function list(array $params)
    {
        $robotId = $params['robot_id'];
        if(empty($robotId)){
            return [];
        }

        $mainUid = $params['main_uid'];

        $robotInfo = $this->robotMapper->findById($robotId);
        if(empty($robotInfo)){
            return [];
        }

        $employeeList = ChEmployee::query()
            ->selectRaw('id,nickname,avatar_url as avatar,corp_name,user_id,0 as is_wechat')
            ->where('main_uid',$mainUid)
            ->where('corp_id',$robotInfo->corp_wxid)
            ->get();
        if($employeeList->isEmpty()){
            $robotApiService = make(Robot::class, [$robotInfo->server_id, $robotInfo->uuid])->gateway();
            $hasMore = true;
            $currentVersion = '';
            $batchData = [];
            while ($hasMore) {
                $response = $robotApiService->getEmployeeList($currentVersion, 1000);
                if($response === false){
                    break;
                }
                $contactList = $response['contact_list'];
                $userIdList = collect($contactList)->filter(function ($item) {
                    return $item['user_id'] !== 0;
                })->pluck('user_id')->toArray();
                $detail = $robotApiService->getEmployeeDetail($userIdList);
                if($detail !== false && !empty($detail['contact_list'])){
                    $detailList = $detail['contact_list'];
                    foreach ($detailList as $k=>$item){
                        $detailList[$k]['main_uid'] = $robotInfo->main_uid;
                        $detailList[$k]['uid'] = $robotInfo->uid;
                        $detailList[$k]['corp_name'] = $robotInfo->corp_name;
                        $detailList[$k]['nickname'] = $item['nickname'];
                        $detailList[$k]['alias'] = $item['alias'];
                        $detailList[$k]['real_name'] = $item['real_name'];
                        $detailList[$k]['job'] = $item['job'];
                        $detailList[$k]['created_at'] = Carbon::now();
                        $detailList[$k]['updated_at'] = Carbon::now();
                    }
                    $batchData = array_merge($batchData, $detailList);
                }
                $hasMore = $response['has_more'];
                $currentVersion = $response['current_version'];
            }

            if(!empty($batchData)){
                ChEmployee::query()->upsert($batchData,['corp_id','user_id']);
            }
            $employeeList = ChEmployee::query()
                ->selectRaw('id,nickname,avatar_url as avatar,corp_name,user_id,0 as is_wechat')
                ->where('main_uid',$mainUid)
                ->where('corp_id',$robotInfo->corp_wxid)
                ->get();
        }

        return [
            'corp_name' => $robotInfo->corp_name,
            'list' => $employeeList,
        ];
    }

    public function searchList(array $params)
    {
        $robotId = $params['robot_id'];

        $keyword = $params['keyword'] ?? '';
        if(empty($robotId)){
            return [];
        }

        $mainUid = $params['main_uid'];

        $robotInfo = $this->robotMapper->findById($robotId);
        if(empty($robotInfo)){
            return [];
        }


        $employeeList = ChEmployee::query()
            ->selectRaw('id,nickname,avatar_url as avatar,user_id,corp_name,0 as is_wechat')
            ->where('main_uid',$mainUid)
            ->where('corp_id',$robotInfo->corp_wxid)
            ->when(!empty($keyword), function ($query) use ($keyword) {
                $query->where('nickname', 'like', "%{$keyword}%");
            });


        $list = ChContact::query()
            ->select(['id','nickname','avatar','user_id','corp_short_name as corp_name','is_wechat'])
            ->union($employeeList)
            ->where('main_uid',$mainUid)
            ->where('robot_id',$robotId)
            ->when(!empty($keyword), function ($query) use ($keyword) {
                $query->where('nickname', 'like', "%{$keyword}%");
            })
            ->get();
        return $list;
    }
}